<?php

namespace seecms\lib;

use Gregwar\Captcha\CaptchaBuilder;
use seecms\lib\response\HtmlResponse;

class Captcha
{
    protected $builder;

    protected $number = '23456789';

    protected $letter = 'qwertyupasdfghjkzxcvbnm';

    public function __construct()
    {
        session_start();
        $this->builder = new CaptchaBuilder();
    }

    public function random($length): string
    {
        $mixed = $this->number . $this->letter;
        $len = strlen($mixed) - 1;
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $mixed[rand(0, $len)];
        }
        return $str;
    }

    public function output($length = null): HtmlResponse
    {
        if ($length === null || $length < 3) {
            $length = rand(4, 6);
        }

        $str = $this->random($length);
        $_SESSION['user_login_captcha'] = $str;
        $this->builder->setPhrase($str);
        $this->builder->build();

        $content = $this->builder->get();

        $header = [
            'Content-Type' => 'image/png',
            'Content-Length' => strlen($content),
        ];

        $response = new HtmlResponse($content, 200);
        $response->header = $header;

        return $response;
    }

    public function check($captcha): bool
    {
        if (!$captcha) {
            return false;
        }

        $captcha = strtolower($captcha);
        if ($captcha == ($_SESSION['user_login_captcha'] ?? '')) {
            return true;
        }
        return false;
    }
}